const glob = require('glob');
const path = require('path');

let COS = require('cos-nodejs-sdk-v5');
// 创建实例
let cos = new COS({
  SecretId: 'AKIDlQs9GApFTVO4VmqgGbkfOwGPJ1VotmTv',
  SecretKey: 'KRYXMzQdcP1QceUAgy5yd3HH2YptkNl8',
});

// 存储桶名称，由bucketname-appid 组成，appid必须填入，可以在COS控制台查看存储桶名称。 https://console.cloud.tencent.com/cos5/bucket
let Bucket = 'order-saas-1338544684';
// 存储桶Region可以在COS控制台指定存储桶的概览页查看 https://console.cloud.tencent.com/cos5/bucket/
// 关于地域的详情见 https://cloud.tencent.com/document/product/436/6224
let Region = 'ap-guangzhou';

const COS_PATH = 'orderSass';
const PROJECT_NAME_PATH = 'dist-cos';

async function uploadFile(fileName) {
  await cos.uploadFile(
    {
      Bucket: Bucket,
      Region: Region,
      Key: COS_PATH + '/' + PROJECT_NAME_PATH + '/' + fileName,
      FilePath: './dist/' + fileName, // 本地文件地址，需自行替换
      SliceSize: 1024 * 1024 * 5, // 触发分块上传的阈值，超过5MB使用分块上传，非必须
    },
    function (err, data) {
      if (err) {
        console.log('[上传失败]', err);
      }
    },
  );
}

async function uploadFiles() {
  try {
    // 遍历 dist 文件夹中的所有文件
    const files = glob.sync('**/*', { cwd: 'dist', nodir: true });
    const remoteBasePath = 'path/to/remote/dist'; // OSS 中的目标路径

    for (const file of files) {
      const localPath = path.join('dist', file); // 本地文件路径
      const remotePath = path.join(remoteBasePath, file); // OSS 中的文件路径
      // 上传文件
      await uploadFile(file);

      console.log(`Uploaded: ${localPath} -> ${remotePath}`);
    }

    console.log('All files uploaded successfully');
  } catch (error) {
    console.error('Error uploading files:', error);
  }
}

uploadFiles();
